package com.xiyou.week03.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 589. N 叉树的前序遍历
 * N 叉树 在输入中按层序遍历进行序列化表示，每组子节点由空值 null 分隔
 *
 * @ClassName：InorderTraversal
 * @Author：西柚
 * @Date：2022/1/13 4:52 下午
 * @Versiion：1.0
 */
public class Preorder {

    static List<Integer> seq;

    /**
     * 输入：root = [1,null,3,2,4,null,5,6]
     * 输出：[1,3,5,6,2,4]
     *
     * @param root
     * @return
     */
    public static List<Integer> preorder(Node root) {
        seq = new ArrayList<>();
        if (root == null) {
            return seq;
        }

        // 迭代法
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            seq.add(node.val);
            for (int i = node.children.size() - 1; i >= 0; i--) {
                stack.push(node.children.get(i));
            }
        }

        // 递归
//        dfs(root);
        return seq;
    }


    static void dfs(Node root) {
        if (root == null) {
            return;
        }
        seq.add(root.val);
        for (Node child : root.children) {
            dfs(child);
        }
    }

    static class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    public static void main(String[] args) {
        Node node = new Node();
    }
}
